package com.rykj.energy.common.utils;

import org.apache.commons.codec.binary.Base64;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import java.security.SecureRandom;
import java.util.Date;

public class DES {

	private String KEY = "HpgYZN6y$krTKcumKotSl%wzDAB3tSc1";
    private String CODE_TYPE = "UTF-8";

	public static void main(String[] args) throws Exception {
		DES des = new DES("HpgYZN6y$krTKcumKotSl%wzDAB3tSc1");
//		System.out.println(des.encode("123456"));
//		System.out.println(des.decode("hWJZMMbNkLI="));
		Date date = new Date();
		Date date1 = DateUtils.addHowMinute(date,30);
		String endTime = DateUtils.getDate(date1);
		System.out.println(endTime);
		String str = 1 + "#" +endTime;
		System.out.println(str);
		System.out.println(des.encode(str));
	}

	/**
	 * 使用默认key： rykj@ETL123
	 */
	public DES() {

	}

	public DES(String key) {
		KEY = key;
	}

	public DES(String key, String charset) {
		KEY = key;
		CODE_TYPE = charset;
	}

	/**
	 * DES加密
	 * @param datasource
	 * @return
	 */
	public String encode(String datasource){
		if(StringUtils.isBlank(datasource)) {
			return null;
		}
	    try{
	        SecureRandom random = new SecureRandom();
	        DESKeySpec desKey = new DESKeySpec(KEY.getBytes(CODE_TYPE));
	        //创建一个密匙工厂，然后用它把DESKeySpec转换成
	        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
	        SecretKey securekey = keyFactory.generateSecret(desKey);
	        //Cipher对象实际完成加密操作
	        Cipher cipher = Cipher.getInstance("DES");
	        //用密匙初始化Cipher对象
	        cipher.init(Cipher.ENCRYPT_MODE, securekey, random);
	        //现在，获取数据并加密
	        byte[] temp = Base64.encodeBase64(cipher.doFinal(datasource.getBytes()));
	        return new String(temp, CODE_TYPE);
	    }catch(Throwable e){
	        e.printStackTrace();
	        return null;
	    }
	}

	/**
	 * DES解密
	 * @return
	 */
	public String decode(String src){
		if(StringUtils.isBlank(src)) {
			return null;
		}
		try {
			// DES算法要求有一个可信任的随机数源
			SecureRandom random = new SecureRandom();
			// 创建一个DESKeySpec对象
			DESKeySpec desKey = new DESKeySpec(KEY.getBytes(CODE_TYPE));
			// 创建一个密匙工厂
			SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
			// 将DESKeySpec对象转换成SecretKey对象
			SecretKey securekey = keyFactory.generateSecret(desKey);
			// Cipher对象实际完成解密操作
			Cipher cipher = Cipher.getInstance("DES");
			// 用密匙初始化Cipher对象
			cipher.init(Cipher.DECRYPT_MODE, securekey, random);
			// 真正开始解密操作
			return new String(cipher.doFinal(Base64.decodeBase64(src)), CODE_TYPE);
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

}
